package com.zff.rental.repository.user;

import com.zff.rental.entity.user.UserEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author HCY
 */
@Repository
public interface UserRepository extends JpaRepository<UserEntity, Long>, JpaSpecificationExecutor<UserEntity> {
    Optional<UserEntity> findOneByPhone(String phone);

    @Query("select u.nickname from UserEntity u where u.userId = ?1")
    String findNicknameByUserId(Long userId);

    default Map<Long, String> findNickname(Iterable<Long> userIdList) {
        if (userIdList == null) {
            return Collections.emptyMap();
        }
        return findNicknameByUserIdIn(userIdList).stream()
                .collect(Collectors.toMap(list -> (Long) list.get(0), list -> (String) list.get(1), (s1, s2) -> s1));
    }

    @Query("select u.userId, u.nickname from UserEntity u where u.userId in ?1")
    List<List<Object>> findNicknameByUserIdIn(Iterable<Long> userIdList);

    boolean existsByAccountName(String accountName);

    boolean existsByPhone(String phone);

    boolean existsByEmail(String email);
}
